package org.lex.collection.tree;

import java.util.Comparator;
import java.util.Iterator;

import org.lex.utils.BinarySearch;
import org.lex.utils.Range;


public class TreeNodeHelper {
	public void sort(ITreeNode node, Comparator<ITreeNode> comparator) {
		for (int i = node.getChildCount() - 1; i > 0; i--) {
			int max = 0;
			for (int j = 1; j <= i; j++) {
				ITreeNode maxNode = node.getChild(max);
				ITreeNode currentNode = node.getChild(j);
				int com = comparator.compare(maxNode, currentNode);
				if (com < 0) {
					max = j;
				}
			}
			node.swap(max, i);
		}
	}

	public ITreeNode searchChild(ITreeNode parent, Object nodeData) {
		for (int i = 0; i < parent.getChildCount(); i++) {
			ITreeNode node = parent.getChild(i);
			if (node.getData().equals(nodeData)) {
				return node;
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public int binarySearchChild(ITreeNode parent, Object nodeData, Comparator nodeDataComparator) {
		Range<Object> range = new TreeNodeRangeAdapter(parent);
		return BinarySearch.search(range, nodeData, nodeDataComparator);
	}

	public Iterator<ITreeNode> getChildren(final ITreeNode node) {
		return new Iterator<ITreeNode>() {
			private int currentIndex = 0;

			@Override
			public boolean hasNext() {
				return currentIndex < node.getChildCount();
			}

			@Override
			public ITreeNode next() {
				return node.getChild(currentIndex++);
			}

			@Override
			public void remove() {
				throw new UnsupportedOperationException("Not implement yet");
			}
		};
	}
}
